package com.songtech.rcs.config.datasource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;


/**
 * Created with IntelliJ IDEA.
 * Description: 主数据源配置
 *
 * @Author: rentie
 * @Date: 2018/8/8 10:30
 */

@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = {"com.songtech.rcs.dao"} , sqlSessionTemplateRef = "rcsSqlSessionTemplate")
public class RcsDataSourceConfig {

    private Logger logger = LoggerFactory.getLogger(RcsDataSourceConfig.class);


    // 精确到 rcs 目录，以便跟其他数据源隔离
    static final String MAPPER_LOCATION = "classpath:mappers/rcs/**/*.xml";
    static final String TYPE_ALIASES_PACKAGE = "com.songtech.rcs.model";


    @Bean("rcsDataSource")
    @ConfigurationProperties("spring.datasource.druid.rcs")
    public DataSource rcsDataSource(){
        logger.info("rcs dataSource init");
        return DruidDataSourceBuilder.create().build();
    }


    @Bean(name = "rcsTransactionManager")
    public DataSourceTransactionManager rcsTransactionManager() {
        return new DataSourceTransactionManager(rcsDataSource());
    }

    @Bean(name = "rcsSqlSessionFactory")
    public SqlSessionFactory rcsSqlSessionFactory(@Qualifier("rcsDataSource") DataSource dataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setTypeAliasesPackage(TYPE_ALIASES_PACKAGE);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

    @Bean(name = "rcsSqlSessionTemplate")
    public SqlSessionTemplate rcsSqlSessionTemplate(@Qualifier("rcsSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}